// /*
//  * @Author: WanYiMing
//  * @Date:2024-07-25-18:15
//  * @Description:
//  */

using System;
using Unity.VisualScripting;
using UnityEngine;
using Random = UnityEngine.Random;

namespace Code.Monster
{
    public class MonsterController : MonoBehaviour
    {
        //首领
        public MonsterLeaderController monsterLeaderController;
        //集结范围
        public float assemblyRadius=0.5f;
        //目标位置        
        private Vector3 _targetPosition;
        public float moveSpeed = 3f;
        private SpaceLine _spaceLine;

        private void Start()
        {
            BoxCollider2D boxCollider2D = this.AddComponent<BoxCollider2D>();
            _spaceLine = this.AddComponent<SpaceLine>();
            _spaceLine.Draw(assemblyRadius);
        }


        private void Update()
        {
            if (monsterLeaderController is null)
            {
                RandomMove();
            }
            else
            {
                FollowMove();
            }
            
            //排斥其他物体
            RejectMonster();
        }

        private void RejectMonster()
        {
            Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, 0.2f);
            foreach (Collider2D collider in colliders)
            {
                if (collider.gameObject != gameObject)
                {
                    // 移动新物体
                    Vector3 dir = gameObject.transform.position - collider.transform.position;
                    dir.Normalize();
                    transform.position = Vector3.Lerp(transform.position, dir, 0.3f * Time.deltaTime);
                }
            }
        }

        private void FollowMove()
        {
            Vector3 targetPosition = monsterLeaderController.transform.position;
            transform.position = Vector3.MoveTowards(transform.position, targetPosition, moveSpeed * Time.deltaTime);
        }


        public bool IsAssembly(MonsterLeaderController tMonsterLeaderController)
        {
            if (monsterLeaderController is null)
            {
                monsterLeaderController = tMonsterLeaderController;
                return true;
            }

            return false;
        }
        
        
        
        
        private void RandomMove()
        {
            if (Vector3.Distance(transform.position, _targetPosition) <= .1f)
            {
                float randomAngle = Random.Range(0f, 2f * Mathf.PI);
                float xOffset = assemblyRadius * Mathf.Cos(randomAngle);
                float yOffset = assemblyRadius * Mathf.Sin(randomAngle);
                _targetPosition = new Vector2(transform.position.x + xOffset, transform.position.y + yOffset);
            }

            transform.position = Vector3.MoveTowards(transform.position, _targetPosition, moveSpeed * Time.deltaTime);
        }
        
        



    }
}